import dayjs, { Dayjs } from 'dayjs'
import { memo, useEffect, useState } from 'react'
import { styled, Access } from '@umijs/max'
import { Modal, Radio, TimePicker } from 'antd'

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;

  .radio {
    width: 100%;
  }

  .time-list {
    width: 100%;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    gap: 8px;

    .item {
      width: 100%;
      display: flex;
      gap: 8px;

      .btn {
        width: 28px;
        flex-shrink: 0;
        display: flex;
        align-item: center;
      }
    }
  }
`

const Hours: number[] = new Array(24).fill(0).map((_,i) => i)
const Minutes: number[] = new Array(60).fill(0).map((_,i) => i)

type Value = [Dayjs, Dayjs]

interface OpeningHoursProps {
  value?: Value[]
  onChange?: (value: Value[]) => void
}

const OpeningHours: React.FC<OpeningHoursProps> = props => {
  const [type, setType] = useState(1)
  const [timeList, setTimeList] = useState<Value[]>([])
  
  const addItem = () => {
    const lastItem = timeList.at(-1)![1]
    const hour = lastItem.hour()
    const minute = lastItem.minute()
    if (hour === 23 && minute === 59) {
      Modal.warn({
        title: '提示',
        content: '已无剩余时间可添加',
      })
      return
    }
    setTimeList(timeList.concat([[lastItem.add(1, 'minute'), dayjs().set('hour', 23).set('minute', 59)]]))
  }

  const remove = (index: number) => {
    setTimeList(timeList.filter((_, idx) => idx !== index))
  }

  const getDisabledTime = (index: number) => {
    const previewEndTime = index === 0 ? dayjs().set('hour', 0).set('minute', 0) : timeList[index-1][1].add(1, 'minute')
    const previewHour = previewEndTime.hour()
    const previewMinute = previewEndTime.minute()
    const nextFirstTime = index === timeList.length - 1 ? dayjs().set('hour', 23).set('minute', 59) : timeList[index+1][0].subtract(1, 'minute')
    const nextHour = nextFirstTime.hour()
    const nextMinute = nextFirstTime.minute()

    return {
      disabledHours: () => Hours.filter(it => it < previewHour || it > nextHour),
      disabledMinutes: (h: number) => {
        if (h === previewHour) {
          return Minutes.filter(it => it < previewMinute)
        } else if (h === nextHour) {
          return Minutes.filter(it => it > nextMinute)
        } else if (h > nextHour || h < previewHour) {
          return Minutes
        }
        return []
      }
    }
  }

  const onTimeChange = (value: Value, index: number) => {
    setTimeList(timeList.map((it, idx) => {
      if (idx === index) return value
      return it
    }))
  }

  useEffect(() => {
    if (timeList.length) {
      props.onChange?.(timeList)
    }
  }, [timeList])

  useEffect(() => {
    if (timeList.length < 1) {
      setTimeList(props.value || [])
    }
    if (props.value?.length) {
      const time = props.value[0]
      if (time[0].hour() !== 0 || time[0].minute() !== 0 || time[1].hour() !== 23 || time[1].minute() !== 59) {
        setType(2)
      } else {
        setType(1)
        setTimeList(props.value || [])
      }
    }
  }, [props.value])

  return (
    <Container>
      <div className='radio'>
        <Radio.Group 
          value={type}
          options={[{label: '全天', value: 1}, {label: '自定义', value: 2}]}
          onChange={({target}) => setType(target.value)}
        />
      </div>
      <div className="time-list">
        {
          timeList.map((item, index) => {
            return (
              <div className="item" key={index}>
                <TimePicker.RangePicker 
                  format={'HH:mm'} disabled={type === 1} 
                  disabledTime={() => getDisabledTime(index)}
                  value={item}
                  onChange={val => onTimeChange(val as Value, index)}
                />
                <div className='btn'>
                  <Access accessible={index > 0 && index === timeList.length - 1}>
                    <a className='btn' onClick={() => remove(index)}>删除</a>
                  </Access>
                </div>
              </div>
            )
          })
        }
        <Access accessible={type === 2}>
          <div className="item">
            <a onClick={addItem}>+添加时间</a>
          </div>
        </Access>
      </div>
    </Container>
  )
}

export default memo(OpeningHours)